package self.hoy.demo.grainmall.ware.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import self.hoy.demo.common.constant.WareConstant;
import self.hoy.demo.common.utils.PageUtils;
import self.hoy.demo.common.utils.Query;

import self.hoy.demo.grainmall.ware.entity.PurchaseDetail;
import self.hoy.demo.grainmall.ware.mapper.PurchaseMapper;
import self.hoy.demo.grainmall.ware.entity.Purchase;
import self.hoy.demo.grainmall.ware.service.PurchaseDetailService;
import self.hoy.demo.grainmall.ware.service.PurchaseService;
import self.hoy.demo.grainmall.ware.service.WareSkuService;
import self.hoy.demo.grainmall.ware.vo.MergeVo;
import self.hoy.demo.grainmall.ware.vo.PurchaseDoneVo;
import self.hoy.demo.grainmall.ware.vo.PurchaseItemDoneVo;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseMapper, Purchase> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<Purchase> page = this.page(
                new Query<Purchase>().getPage(params),
                new QueryWrapper<Purchase>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        QueryWrapper<Purchase> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 0).or().eq("status", 1);//TODO 枚举
        IPage<Purchase> page = this.page(
                new Query<Purchase>().getPage(params), wrapper
        );
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        Purchase purchase = new Purchase();
        if (purchaseId == null) {
            purchase.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchase.setCreateTime(new Date());
            purchase.setUpdateTime(purchase.getCreateTime());
            this.save(purchase);
            mergeVo.setPurchaseId(purchase.getId());
        } else {
            //TODO 确认采购单状态 0 / 1 才能进行下一步
            purchase.setId(purchaseId);
            purchase.setUpdateTime(new Date());
            updateById(purchase);
        }
        List<Long> items = mergeVo.getItems();
        List<PurchaseDetail> details = items.stream().map(i -> {
            PurchaseDetail detail = new PurchaseDetail();
            detail.setId(i);
            detail.setPurchaseId(mergeVo.getPurchaseId());
            detail.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detail;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(details);
    }

    @Override
    @Transactional
    public void receive(List<Long> ids) {
        // 确认当前采购单是新建或者已分配状态
        List<Purchase> collect = ids.stream().map(id -> {
            Purchase byId = getById(id);
            return byId;
        }).filter(item -> {
            return item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                    || item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode();
        }).map(item->{
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            return item;
        }).collect(Collectors.toList());

        // 改变采购单的状态
        this.updateBatchById(collect);

        // 改变采购项的状态
        collect.forEach(item->{
            List<PurchaseDetail> details = purchaseDetailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetail> detailList = details.stream().map(d -> {
                PurchaseDetail detail = new PurchaseDetail();
                detail.setId(d.getId());
                detail.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return detail;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(detailList);
        });
    }

    @Override
    @Transactional
    public void finish(PurchaseDoneVo purchaseFinishVo) {
        //改变采购单状态
        Long id = purchaseFinishVo.getId();

        List<PurchaseItemDoneVo> items = purchaseFinishVo.getItems();
        List<PurchaseDetail> updates = new ArrayList<>();
        boolean success = true;
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetail pd = new PurchaseDetail();
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HAS_ERROR.getCode()) {
                success = false;
                pd.setStatus(item.getStatus());
            } else {
                pd.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());

                PurchaseDetail detail = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum());
            }
            pd.setId(item.getItemId());
            updates.add(pd);
        }
        purchaseDetailService.updateBatchById(updates);

        //
        Purchase purchase = new Purchase();
        purchase.setId(id);
        purchase.setUpdateTime(new Date());
        purchase.setStatus((success ? WareConstant.PurchaseStatusEnum.FINISH : WareConstant.PurchaseStatusEnum.HAS_ERROR).getCode());
        this.updateById(purchase);

        //将成功的入库

    }

}